/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package smsserver.manager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author ZHENG ZHI YOU
 */
public class DbManager {
    static DbManager dbManager = null;

    private Connection conn = null;
    private Statement statement = null;
    public static DbManager getInstance()
    {
        if(dbManager == null)
        {
            dbManager = new DbManager();
        }
        return dbManager;
    }

    DbManager()
    {
        initDb();
    }

    private void initDb()
    {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String url = "jdbc:odbc:Driver={Microsoft Access Driver " +
                    "(*.mdb, *.accdb)};DBQ=C:\\db.accdb";
            conn = DriverManager.getConnection(url);
            statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
            System.out.println("Connected!");            
        } catch (SQLException e) {
            System.out.println("SQL Exception: "+ e.toString());
        } catch (ClassNotFoundException cE) {
            System.out.println("Class Not Found Exception: "+ cE.toString());
        }
    }

    public boolean selectWhere(String iccid)
    {
        try {
            String sqlstr = "select * from user where iccid ='"+iccid+"'";
            ResultSet rs = statement.executeQuery(sqlstr);
            if(getCount(rs)>0)
            {
                return true;
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return false;
    }

    public ResultSet excutesql(String strsql)
    {
        System.out.println(strsql);
        try {          
            ResultSet rs = statement.executeQuery(strsql);
            return rs;
        } catch (SQLException ex) {
            Logger.getLogger(DbManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }




    public int getCount(ResultSet rs)
    {
        if(rs==null)
        {
            System.out.println("null");
            return 0;
        }
        int rows = 0;
        try {
            rs.last();
            rows = rs.getRow();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return rows;
    }

    public void closeDb()
    {
        try {
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(DbManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
